<?php

/**
 * Example to dumping data into a CSV file using Stream_Iterate as stream
 *
 * PHP version 5
 *
 * @category  Stream
 * @package   Stream_Iterate
 * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
 * @copyright 2008 11abacus / Philippe Jausions
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
 * @link      http://pear.11abacus.com/package/Stream_Iterate
 */

/**
 * Required packages
 */
require_once 'Stream/Iterate.php';
require_once 'System/Folders.php';

/**
 * Defines a CSV "printer"
 *
 * @param array   $value     List of data to print out
 * @param integer $iteration Iteration counter (zero-based)
 *
 * @return string the CSV string
 */
function toCSVString(array $value, $iteration)
{
    static $headers = array();

    $result = '';
    if ($iteration === 0) {
        $headers = array_keys($value);
        $result  = implode(',', $headers)."\n";
    }
    foreach ($headers as $header) {
        $result .= '"'.str_replace('"', '""', $value[$header]).'",';
    }

    return substr($result, 0, -1)."\n";
}

/**
 * Main
 */
stream_wrapper_register('foreach', 'Stream_Iterate');

$data = array(array('firstname' => 'John',
                    'lastname'  => 'Doe',
                    'city'      => 'Towneville'),
              array('lastname'  => 'Doe',
                    'city'      => 'Citybourg',
                    'firstname' => 'Jane'));

$context = stream_context_create(array(
    'foreach' => array(
        'data' => $data,
        'toString' => 'toCSVString', // Called to format data into string
    ),
));

$sf = new System_Folders();

$tempFile = tempnam($sf->getTemp(), 'MyFile');

// Just for awareness :-)
if (version_compare(phpversion(), '6.0.0', '>=')) {
    $flag = 0;
} else {
    $flag = false;
}

file_put_contents('compress.zlib://'.$tempFile.'.gz', 
                  file_get_contents('foreach://value@data', $flag, $context));

echo 'Data dumped to '.$tempFile.'.gz';

?>